/**
 * 公告公示相关的API hooks
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/services/api';
import { Announcement, AnnouncementCreate, AnnouncementUpdate } from '@/types';

// API响应类型
interface AnnouncementsResponse {
  items: Announcement[];
  total: number;
  page: number;
  size: number;
  pages: number;
}

interface UseAnnouncementsParams {
  keyword?: string;
  category?: string;
  published_only?: boolean;
  page?: number;
  size?: number;
}

// 获取公告列表
export function useAnnouncements(params: UseAnnouncementsParams = {}) {
  const {
    keyword = '',
    category = '',
    published_only = false,
    page = 1,
    size = 10
  } = params;

  return useQuery<AnnouncementsResponse>({
    queryKey: ['announcements', { keyword, category, published_only, page, size }],
    queryFn: async () => {
      const searchParams = new URLSearchParams();
      
      if (keyword) searchParams.append('keyword', keyword);
      if (category) searchParams.append('category', category);
      if (published_only) searchParams.append('published_only', 'true');
      searchParams.append('page', page.toString());
      searchParams.append('size', size.toString());

      const response = await api.get(`/api/announcements/?${searchParams.toString()}`);
      return response;
    },
    staleTime: 5 * 60 * 1000, // 5分钟
  });
}

// 获取单个公告详情
export function useAnnouncement(id: number) {
  return useQuery<Announcement>({
    queryKey: ['announcement', id],
    queryFn: async () => {
      const response = await api.get(`/api/announcements/${id}`);
      return response;
    },
    enabled: !!id,
    staleTime: 5 * 60 * 1000,
  });
}

// 创建公告
export function useCreateAnnouncement() {
  const queryClient = useQueryClient();

  return useMutation<Announcement, Error, AnnouncementCreate>({
    mutationFn: async (data) => {
      const response = await api.post('/api/announcements/', data);
      return response;
    },
    onSuccess: () => {
      // 刷新公告列表
      queryClient.invalidateQueries({
        queryKey: ['announcements'],
        exact: false
      });
    },
  });
}

// 更新公告
export function useUpdateAnnouncement() {
  const queryClient = useQueryClient();

  return useMutation<Announcement, Error, { id: number; data: AnnouncementUpdate }>({
    mutationFn: async ({ id, data }) => {
      const response = await api.put(`/api/announcements/${id}`, data);
      return response;
    },
    onSuccess: (data) => {
      // 刷新公告列表
      queryClient.invalidateQueries({
        queryKey: ['announcements'],
        exact: false
      });
      // 更新单个公告缓存
      queryClient.setQueryData(['announcement', data.id], data);
    },
  });
}

// 删除公告
export function useDeleteAnnouncement() {
  const queryClient = useQueryClient();

  return useMutation<void, Error, number>({
    mutationFn: async (id) => {
      await api.delete(`/api/announcements/${id}`);
    },
    onSuccess: () => {
      // 刷新公告列表
      queryClient.invalidateQueries({
        queryKey: ['announcements'],
        exact: false
      });
    },
  });
}

// 切换公告发布状态
export function useToggleAnnouncementStatus() {
  const queryClient = useQueryClient();

  return useMutation<Announcement, Error, { id: number; is_published: boolean }>({
    mutationFn: async ({ id, is_published }) => {
      const response = await api.patch(`/api/announcements/${id}/status`, { is_published });
      return response;
    },
    onSuccess: (data) => {
      // 刷新公告列表
      queryClient.invalidateQueries({
        queryKey: ['announcements'],
        exact: false
      });
      // 更新单个公告缓存
      queryClient.setQueryData(['announcement', data.id], data);
    },
  });
}
